package chzhenjia.learn.androidcode.two;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import chzhenjia.learn.androidcode.R;

/**
 * SharedPreference的演示
 *
 * @author 陈圳佳
 *         日期:2015/7/14
 */
public class LoginActivity extends AppCompatActivity {

    private CheckBox ckRemember;
    private TextView etPassword;
    private TextView etUsername;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.login_btn_login:
                    login();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        readConfig();
    }

    private void init() {
        Button btnLogin = (Button) findViewById(R.id.login_btn_login);
        ckRemember = (CheckBox) findViewById(R.id.login_ck_remember);
        etPassword = (TextView) findViewById(R.id.login_et_password);
        etUsername = (TextView) findViewById(R.id.login_et_username);

        btnLogin.setOnClickListener(onClickListener);
    }

    private void readConfig() {
        SharedPreferences info = getSharedPreferences("info", MODE_PRIVATE);
        String user = info.getString("user", "");
        String pass = info.getString("pass", "");
        etPassword.setText(pass);
        etUsername.setText(user);
    }

    private void login() {
        String password = etPassword.getText().toString().trim();
        String username = etUsername.getText().toString().trim();
        Toast.makeText(this, "登录成功！", Toast.LENGTH_SHORT).show();

//      如果多选框没有选中则直接中断该方法  
        if (!ckRemember.isChecked()) {
            return;
        }
        SharedPreferences info = getSharedPreferences("info", MODE_PRIVATE);
        SharedPreferences.Editor edit = info.edit();
        edit.putString("user", username);
        edit.putString("pass", password);
        edit.apply();
    }
}
